package com.yzw.common.security;

import com.yzw.common.service.impl.EduAclUserServiceImpl;
import com.yzw.common.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Yzw
 * @Description TODO
 * @Date 2023/5/15 15:23
 * @Version 1.0
 */
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private EduAclUserServiceImpl userInfoServie;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authToken = request.getHeader(tokenHeader);
        //存在token
        if (null != authToken && authToken.startsWith(tokenHead)) {

            String token = authToken.substring(tokenHead.length());

            String username = jwtTokenUtil.getUserNameFromToken(token);

            UserDetails userDetails = userInfoServie.loadUserByUsername(username);
            //验证token是否有效，重新设置用户对象
            if (jwtTokenUtil.validateToken(token)) {
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }

        }
        filterChain.doFilter(request, response);

    }
}
